package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.entity.SysUser;
import com.example.springboot.entity.dto.UserDTO;
import com.example.springboot.entity.vo.UserPageVO;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author: jyf2000jyf
 * @Date: 2022/4/27
 * @Time: 15:59
 * @Email: 904593011@qq.com
 * @Description:
 **/
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    // 新增和修改
    @PostMapping
    public Result save(@RequestBody SysUser user) {
        // 新增或者更新
        return Result.success(userService.save(user));
    }

    // 查询所有数据
    @GetMapping
    public Result index() {
        List<SysUser> all = userService.findAll();
        return Result.success(all);
    }

    @GetMapping("user")
    public Result getUserAmount() {
        Integer userAmount = userService.getUserAmount();
        return Result.success(userAmount);
    }

    @GetMapping("delete")
    public Result delete(@RequestParam Integer id) {
        userService.delete(id);
        return Result.success(true);
    }

    @PostMapping("delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            userService.delete(id);
        }
        return Result.success(true);
    }

    @GetMapping("page")
    public Result indexByPage(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              @RequestParam String username,
                              @RequestParam String email,
                              @RequestParam String contactPerson) {
        pageNum = (pageNum - 1) * pageSize;
        List<SysUser> data = userService.findAll(pageNum, pageSize, username, email, contactPerson);
        Integer total = userService.getAmount(username, email, contactPerson);
        return Result.success(new UserPageVO(data, total));
    }

    @GetMapping("export")
    public Result export(HttpServletResponse response) throws IOException {
        // 从数据库查询出所有的数据
        List<SysUser> list = userService.findAll();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名，此处在SysUser类里使用了@Alias注解
        // writer.addHeaderAlias("username", "用户名");
        // writer.addHeaderAlias("password", "密码");
        // writer.addHeaderAlias("nickname", "昵称");
        // writer.addHeaderAlias("email", "邮箱");
        // writer.addHeaderAlias("phone", "电话");
        // writer.addHeaderAlias("address", "地址");
        // writer.addHeaderAlias("createTime", "创建时间");
        // writer.addHeaderAlias("avatarUrl", "头像");
        // writer.addHeaderAlias("role", "角色");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
        return Result.success(true);
    }

    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象
        List<SysUser> users = reader.readAll(SysUser.class);
        userService.saveBatch(users);
        return Result.success(true);
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.login(userDTO));
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.register(userDTO));
    }

    @GetMapping("/username")
    public Result getUserInfo(@RequestParam String username) {
        return Result.success(userService.getUserInfo(username));
    }

    @GetMapping("/newUser")
    public Result getNewUser() {
        return Result.success(userService.getNewUser());
    }
}
